package com.hm.common.config;

import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 短链Apollo配置
 *
 * @author 020102
 * @date 2020-04-14 15:09
 */
@Data
@ComponentScan
@Component
@ConfigurationProperties(prefix = "hm.short-url.auth")
public class AuthConfig {

    private Gson gson = new Gson();
    /**
     * 权限json数组
     */
    private String tokens;

    /**
     * 以token为key,AuthDTO为value生成的一个map
     */
    private Map<String, AuthDTO> authMap;


    @PostConstruct
    void init() {
        ArrayList<AuthDTO> arrayList =  (ArrayList<AuthDTO>)new Gson().fromJson(tokens, new TypeToken<ArrayList<AuthDTO>>() {}.getType());
        this.authMap = arrayList.stream().collect(Collectors.toMap(k -> k.getToken(), k -> {
            /*  给每个token初始化一个RateLimiter */
            k.setRateLimiter(RateLimiter.create(k.getLimit()));
            return k;
        }, (k1, k2) -> k1));
    }

    @Data
    public static class AuthDTO {
        /**
         * 来源 如:APP
         */
        public String from;
        /**
         * 校验token
         */
        public String token;
        /**
         * 限流qps
         */
        public Double limit;

        /**
         * 限流器,再init方法中根据limit的大小初始化的
         */
        private RateLimiter rateLimiter;
    }

}
